#!/usr/bin/env python
# coding: utf-8

# ## 高德地图Web服务 API
# 
# - 文档：https://lbs.amap.com/api/webservice/summary/
# 
# 共13个功能，29个子功能

# In[ ]:


# 地理编码

import requests

# 封装--> geocode函数
def geocode(address,city=None,batch=None,sig=None)->dict:
    """获取地理编码"""
    key = "你的key"
    url = 'https://restapi.amap.com/v3/geocode/geo?parameters' # API服务地址
    params={
        'key': key,
        'address':address,
        'city':city,
        'batch':batch, #批量查询控制
        'sig':sig, #数字签名
        'output':'json' #返回数据格式类型
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 逆地理编码

import requests

# 封装--> regeocode函数
def regeocode(location,poitype=None,radius=None,extensions="base",batch=False,roadlevel=None,sig=None,homeorcorp=None)->dict:
    """获取逆地理编码"""
    key = "你的key"
    url = 'https://restapi.amap.com/v3/geocode/regeo?parameters' #API服务地址
    params={
        'key': key,
        'location':location,
        'poitype':poitype, #返回附近POI类型
        'radius':radius, #搜索半径
        'extensions':extensions, #返回结果控制
        'batch':batch, #批量查询控制
        'roadlevel':roadlevel, #道路等级
        'homeorcorp':homeorcorp, #是否优化POI返回顺序
        'sig':sig, #数字签名
        'output':'json' #返回数据格式类型
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 步行路径规划

import requests

# 封装--> walking函数
def walking(origin,destination,sig=None)->dict:
    """获取步行路径规划"""
    key = "你的key"
    url = 'https://restapi.amap.com/v3/direction/walking?parameters'
    params={
        'key':key,
        'origin':origin, #起点坐标
        'destination':destination, #终点坐标
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 公交路径规划

import requests

# 封装-->integrated函数
def integrated(origin,destination,city,cityd=None,extensions='base',strategy=None,nightflag=0,date=None,time=None,sig=None)->dict:
    """获取公交路径规划"""
    key = "你的key"
    url = 'https://restapi.amap.com/v3/direction/transit/integrated?parameters'
    params={
        'key':key,
        'origin':origin,
        'destination':destination,
        'city':city,
        'cityd':cityd,#跨城公交规划时的终点城市
        'extensions':extensions,#返回结果详略
        'strategy':strategy, #公交换乘策略
        'nightflag':nightflag,#是否计算夜班车
        'date':date,#出发日期
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 驾车路径规划

import requests

# 封装--> driving函数
def driving(origin,destination,extensions='base',originid=None,destinationid=None,origintype=None,destinationtype=None,strategy=0,waypoints=None,avoidpolygons=None,
            avoidroad=None,province=None,number=None,cartype=0,ferry=0,nosteps=0,roadaggregation='false',sig=None,callback=None)->dict:
    """获取驾车路径规划"""
    key = "你的key"
    url='https://restapi.amap.com/v3/direction/driving?parameters'
    params={
        'key':key,
        'origin':origin,
        'destination':destination,
        'originid':originid, #出发点poiid
        'destinationid':destinationid, #目的地poiid
        'origintype':origintype, #起点的poi类别
        'destinationtype':destinationtype, #终点的poi类别
        'strategy':strategy, #驾车选择策略
        'waypoints':waypoints, #途经点
        'avoidpolygons':avoidpolygons, #避让区域
        'avoidroad':avoidroad, #避让道路名
        'province':province, #用汉字填入车牌省份缩写，用于判断是否限行
        'number':number, #用汉字填入车牌省份缩写，用于判断是否限行
        'cartype':cartype, #车辆类型
        'ferry':ferry, #在路径规划中，是否使用轮渡
        'nosteps':nosteps, #是否返回steps字段内容
        'roadaggregation':roadaggregation, #是否返回路径聚合信息
        'output':'json'        
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 骑行路径规划

import requests

# 封装--> bicycling函数
def bicycling(origin,destination)->dict:
    """获取骑行路径规划"""
    key = "你的key"
    url='https://restapi.amap.com/v4/direction/bicycling?parameters'
    params={
        'key':key,
        'origin':origin,
        'destination':destination      
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 货车路径规划

import requests

# 封装--> truck函数
def truck(origin,destination,originid=None,destinationid=None,originidtype=None,destinationtype=None,diu=None,strategy=1,waypoints=None,size=2,province=None,number=None,cartype=0,showpolyline=1,nosteps=0,
          avoidpolygons=None,height=1.6,width=2.5,load=0.9,weight=10,axis=2)->dict:
    """获取货车路径规划"""
    key = "你的key"
    url='https://restapi.amap.com/v4/direction/truck?parameters'
    params={
        'key':key,
        'origin':origin,
        'destination':destination,
        'originid':originid, #出发POI的唯一编号 
        'destinationid':destinationid, #终点POI的唯一编号 
        'originidtype':originidtype, #出发POI的类型 
        'destinationtype':destinationtype, #终点POI的类型 
        'avoidpolygons':avoidpolygons, #避让区域 
        'diu':diu, #设备唯一编号
        'strategy':strategy, #驾车选择策略
        'waypoints':waypoints, #途经点
        'size':size, #车辆大小
        'province':province, #车牌省份
        'number':number, #车牌详情
        'cartype':cartype, #车辆类型
        'height':height, #车辆高度
        'width':width, #车辆宽度
        'load':load, #车辆总重
        'weight':weight, #货车核定载重
        'axis':axis, #车辆轴数
        'showpolyline':showpolyline, #是否返回路线数据
        'nosteps':nosteps #是否返回steps字段内容    
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 距离测量

import requests

# 封装--> distance函数
def distance(origins,destination,type=1,sig=None,callback=None)->dict:
    """获取距离"""
    key = "你的key"
    url='https://restapi.amap.com/v3/distance?parameters'
    params={
        'key':key,
        'origins':origins,
        'destination':destination,
        'type':type, #路径计算的方式和方法 0:直线距离 1:驾车导航距离（仅支持国内坐标） 3:步行规划距离（仅支持5km之间的距离）
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 行政区域查询

import requests

# 封装--> district函数
def district(keywords=None,subdistrict=1,page=1,offset=20,extensions='base',filter='adcode',callback=None)->dict:
    """查询行政区域"""
    key = "你的key"
    url='https://restapi.amap.com/v3/config/district?parameters'
    params={
        'key':key,
        'keywords':keywords, #查询关键字 只支持单个关键词语搜索关键词支持：行政区名称、citycode、adcode
        'subdistrict':subdistrict, #子级行政区 0:不返回下级行政区；1:返回下一级行政区；2:返回下两级行政区；3:返回下三级行政区
        'page':page, #需要第几页数据
        'offset':offset, #最外层返回数据个数
        'extensions':extensions, #返回结果控制 base:不返回行政区边界坐标点；all:只返回当前查询district的边界值，不返回子节点的边界值；
        'filter':filter, #根据区划过滤
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 关键字搜索

import requests

# 封装--> text函数
def text(keywords=None,types=None,city=None,citylimit='false',children=0,page=1,offset=20,extensions='base',callback=None)->dict:
    """关键字搜索"""
    key = "你的key"
    url='https://restapi.amap.com/v3/place/text?parameters'
    params={
        'key':key,
        'keywords':keywords, #查询关键字
        'types':types, #查询POI类型
        'city':city, 
        'citylimit':citylimit, #仅返回指定城市数据
        'children':children, #是否按照层级展示子POI数据
        'page':page, #当前页数
        'offset':offset, #每页记录数据
        'extensions':extensions, #返回结果控制 
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 周边搜索

import requests

# 封装--> around函数
def around(location,keywords=None,types=None,city=None,sortrule='distance',radius=3000,page=1,offset=20,extensions='base',callback=None)->dict:
    """周边搜索"""
    key = "你的key"
    url='https://restapi.amap.com/v3/place/around?parameters'
    params={
        'key':key,
        'keywords':keywords, #查询关键字
        'location':location, #中心点坐标
        'types':types, #查询POI类型
        'city':city, 
        'radius':radius,#查询半径
        'sortrule':sortrule,#排序规则
        'page':page, #当前页数
        'offset':offset, #每页记录数据
        'extensions':extensions, #返回结果控制 
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 多边形搜索

import requests

# 封装--> polygon函数
def polygon(types=None,polygon=None,keywords=None,page=1,offset=20,extensions='base',callback=None)->dict:
    """多边形搜索"""
    key = "你的key"
    url='https://restapi.amap.com/v3/place/polygon?parameters '
    params={
        'key':key,
        'keywords':keywords, #查询关键字
        'types':types, #查询POI类型        
        'polygon':polygon,
        'page':page, #当前页数
        'offset':offset, #每页记录数据
        'extensions':extensions, #返回结果控制 
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


#  ID查询

import requests

# 封装--> detail函数
def detail(id,sig=None,callback=None)->dict:
    """ID查询"""
    key = "你的key"
    url='https://restapi.amap.com/v3/place/detail?parameters'
    params={
        'key':key,
        'id':id, #兴趣点ID
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# IP定位

import requests

# 封装--> ip函数
def ip(ip=None,sig=None)->dict:
    """ip定位"""
    key = "你的key"
    url='https://restapi.amap.com/v3/ip?parameters'
    params={
        'key':key,
        'ip':ip, #ip地址(仅支持国内)
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 批量请求接口

import requests

# 封装--> batch函数
def batch()->dict:
    """批量接口通过用户传入合并后的请求，同时返回多个请求的顺序集合"""
    url='https://restapi.amap.com/v3/batch'
    headers = {'Content-Type': 'application/json'}
    body= {
    "ops": [
        {
            "url": "/v3/place/around?offset=10&page=1&key=<您的key>&location=116.50394379585519,39.278209477408794&output=json&radius=100000&types=080000"
        },
        {
            "url": "/v3/place/around?offset=10&page=1&key=<您的key>&location=118.50394379585519,39.278209477408794&output=json&radius=100000&types=080000"
        }
    ]
}
    params={
        'key':key,
        'output':'json'
    }
    response = requests.post(url,json=body,params=params)
    data = response.json()
    return data


# In[ ]:


#静态地图

import requests

key = "你的key"

# 封装--> staticmap函数
def staticmap(location,zoom=None,size=None,scale=1,markers=None,labels=None,paths=None,traffic=0,page=None,sig=None)->dict:
    """获取静态地图"""
    url = 'https://restapi.amap.com/v3/staticmap?parameters'
    params={
        'key':key,
        'location':location,
        'zoom':zoom, #地图缩放级别:[1,17]
        'size':size, #地图大小
        'scale':scale, #普通/高清
        'markers':markers, #标注
        'labels':labels, #标签
        'paths':paths, #折线
        'traffic':traffic, #交通路况标识
        'sig':sig,
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = Image.open(BytesIO(response.content))
    return data


# In[ ]:


# 坐标转换

import requests

key = "你的key"

# 封装--> convert函数
def convert(locations,coordsys='autonavi',sig=None)->dict:
    """将非高德坐标转换为高德坐标"""
    url = 'https://restapi.amap.com/v3/assistant/coordinate/convert?parameters'
    params={
        'key':key,
        'locations':locations,
        'coordsys':coordsys, #原坐标系：可选值：gps、mapbar、baidu、autonavi(不进行转换)
        'sig':sig,
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 天气查询

import requests

key = "你的key"

# 封装--> weatherInfo函数
def weatherInfo(city,extensions=None)->dict:
    """查询目标区域当前/未来的天气情况"""
    url = 'https://restapi.amap.com/v3/weather/weatherInfo?parameters'
    params={
        'key':key,
        'city':city, #城市编码(需在文档下载)
        'extensions':extensions, #气象类型 base:返回实况天气 all:返回预报天气
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 输入提示

import requests

key = "你的key"

# 封装--> inputtips函数
def inputtips(keywords,type=None,location=None,city=None,citylimit='false',datatype='all',callback=None,sig=None)->dict:
    """根据用户输入的关键词查询返回建议列表"""
    url = 'https://restapi.amap.com/v3/assistant/inputtips?parameters'
    params={
        'key':key,
        'keywords':keywords,
        'type':type, #POI分类 (需在文档下载)
        'location':location, #坐标
        'city':city, #搜索城市
        'citylimit':citylimit, #仅返回指定城市数据
        'datatype':datatype, #返回的数据类型 all-返回所有数据类型、poi-返回POI数据类型、bus-返回公交站点数据类型、busline-返回公交线路数据类型
        'sig':sig,
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 矩形区域交通态势

import requests

key = "你的key"

# 封装--> rectangle函数
def rectangle(rectangle,level=5,extensions='base',callback=None,sig=None)->dict:
    """根据用户输入的内容能够返回希望查询的交通态势情况"""
    url = 'https://restapi.amap.com/v3/traffic/status/rectangle?parameters'
    params={
        'key':key,
        'rectangle':rectangle, #代表此为矩形区域查询
        'extensions':extensions,
        'level':level, #道路等级
        'sig':sig,
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 圆形区域交通态势

import requests

key = "你的key"

# 封装--> circle函数
def circle(location,radius=1000,level=5,extensions='base',callback=None,sig=None)->dict:
    """根据用户输入的内容能够返回希望查询的交通态势情况"""
    url = 'https://restapi.amap.com/v3/traffic/status/circle?parameters'
    params={
        'key':key,
        'location':location, #中心点坐标
        'radius':radius,#半径 (米)
        'extensions':extensions,
        'level':level, #道路等级
        'sig':sig,
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 指定线路交通态势

import requests

key = "你的key"

# 封装--> road函数
def road(name,city=None,adcode=None,level=5,extensions='base',callback=None,sig=None)->dict:
    """根据用户输入的内容能够返回希望查询的交通态势情况"""
    url = 'https://restapi.amap.com/v3/traffic/status/road?parameters'
    params={
        'key':key,
        'name':name, #道路名
        'city':city, #城市名
        'adcode':adcode, #城市编码
        'extensions':extensions,
        'level':level, #道路等级
        'sig':sig,
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 创建地理围栏

import requests

# 封装--> create函数
def create()->dict:
    """创建地理围栏,获取gid"""
    key = "你的key"
    url = 'https://restapi.amap.com/v4/geofence/meta'
    # 请求主体
    body = {
        "name": "测试围栏名称",
        "center": "115.672126,38.817129",
        "radius": "2100",
        "enable": "true",
        "valid_time": "2022-04-19",
        "repeat": "Mon,Tues,Wed,Thur,Fri,Sat,Sun",
        "time": "00:00,11:59;13:00,20:59",
        "desc": "测试围栏描述",
        "alert_condition": "enter;leave"
    }
    # 请求参数
    params = {
        'key':key,
        'output':'json'
    }
    r = requests.post(url,json=body,params=params)
    print(r.status_code)
    data = r.json()
    return data


# In[ ]:


# 查询地理围栏

import requests

# 封装--> search函数
def search(id=None,gid=None,name=None,page_no=1,page_size=20,enable=None,start_time=None,end_time=None)->dict:
    """查询地理围栏"""
    key = "你的key"
    url = 'https://restapi.amap.com/v4/geofence/meta'
    params={
        'key':key,
        'id':id, 
        'gid':gid,
        'name':name,
        'page_no':page_no, 
        'page_size':page_size,
        'enable':enable,
        'start_time':start_time,
        'end_time':end_time,
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 更新地理围栏

import requests

# 封装--> update函数
def update()->dict:
    """更新地理围栏"""
    key = "你的key"
    url = 'https://restapi.amap.com/v4/geofence/meta'
    gid = '89613f1e-7297-4c89-b46c-de6a880f821e'
    # 请求主体
    body = {
        "name": "更新圆形围栏", #必填
        "center": "116.328037,39.962379",
        "radius": "1148.8",
        "valid_time": "2022-06-30",
        "repeat": "Mon,Wed,Fri,Sat,Sun",
        "time": "07:00,12:00;15:00,21:00",
        "desc": "更新圆形围栏描述",
        "alert_condition": "enter"
    }
    # 请求参数
    params = {
        'key':key,
        'gid':gid,
        'output':'json'
    }
    r = requests.patch(url,json=body,params=params) #注：patch方法
    print(r.status_code)
    data = r.json()
    return data


# In[ ]:


# 启动/停止地理围栏

import requests

# 封装--> startstop函数
def startstop()->dict:
    """启动\停止地理围栏"""
    key = "你的key"
    url = 'https://restapi.amap.com/v4/geofence/meta'
    gid = '89613f1e-7297-4c89-b46c-de6a880f821e'
    # 请求主体
    body = {
        "enable": "false" #围栏激活状态；不能与更新围栏参数同时存在
    }
    # 请求参数
    params = {
        'key':key,
        'gid':gid,
        'output':'json'
    }
    r = requests.patch(url,json=body,params=params) #注：patch方法
    print(r.status_code)
    data = r.json()
    return data


# In[ ]:


# 删除地理围栏

import requests

# 封装--> delete函数
def delete()->dict:
    """删除地理围栏"""
    key = "你的key"
    url = 'https://restapi.amap.com/v4/geofence/meta'
    gid = '89613f1e-7297-4c89-b46c-de6a880f821e'
    # 请求主体(放上对应gid的围栏信息，可在查询围栏找到)
    body = {
        "name": "更新圆形围栏", 
        "center": "116.328037,39.962379",
        "radius": "1148.8",
        "valid_time": "2022-06-30",
        "repeat": "Mon,Wed,Fri,Sat,Sun",
        "time": "07:00,12:00;15:00,21:00",
        "desc": "更新圆形围栏描述",
        "alert_condition": "enter"
    }
    # 请求参数
    params = {
        'key':key,
        'gid':gid,
        'output':'json'
    }
    r = requests.delete(url,json=body,params=params) #注：delete方法
    print(r.status_code)
    data = r.json()
    return data


# In[ ]:


# 围栏设备监控

import requests

# 封装--> status函数
def status(diu,locations,uid=None,sig=None)->dict:
    """查询设备与附近的围栏交互状态"""
    key = "你的key"
    url = 'https://restapi.amap.com/v4/geofence/status'
    params={
        'key':key,
        'diu':diu, #用户设备唯一标识符
        'locations':locations, #设备位置坐标组 数据为坐标数据和坐标产生的时间戳数据，至少包含一个坐标对和时间戳。
        'uid':uid, #设备在开发者自有系统中的id
        'sig':sig,
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data


# In[ ]:


# 轨迹纠偏

import requests

# 封装--> grasproad函数
def grasproad()->dict:
    """根据用户输入的内容能够返回希望查询的交通态势情况"""
    key = "你的key"
    url = 'https://restapi.amap.com/v4/grasproad/driving'
    # 请求主体 (注意这里是字典)
    body=[
        {"x": 116.449429,"y": 40.014844,"sp": 4,"ag": 110,"tm": 1478831753}, 
        {"x": 116.449639,"y": 40.014776,"sp": 3,"ag": 110,"tm": 23}, 
        {"x": 116.449859,"y": 40.014716,"sp": 3,"ag": 111,"tm": 33}, 
        {"x": 116.450074,"y": 40.014658,"sp": 3,"ag": 110,"tm": 31},
        {"x": 116.450273,"y": 40.014598,"sp": 3,"ag": 111,"tm": 20}
    ]
    params={
        'key':key,
        'output':'json'
    }
    response = requests.post(url,json=body,params=params)
    data = response.json()
    return data

